<?php
namespace User\Controller;

use Think\Dispatcher;
use Think\Page;
use User\Model\DailySignModel;
use User\Model\FactoryModel;
use Wap\Model\StatisticsModel;

class DailySignController extends UserController
{
    public function __construct()
    {
        parent::__construct();
        if (!headers_sent() && // 如果页面头部信息还没有输出
            extension_loaded('zlib') && // 而且php已经加载了zlib扩展
            strstr($_SERVER['HTTP_ACCEPT_ENCODING'], 'gzip')
        ) //而且浏览器接受GZIP
        {
            ini_set('zlib.output_compression', 'On');
            ini_set('zlib.output_compression_level', '4');
        }
    }

    public function index()
    {
        $daily_sign = M('daily_sign');
        $where['token'] = $this->wxuser['token'];
        $where['status'] = array('NEQ', DailySignModel::SIGN_STATUS_DELETE);
        $count = $daily_sign->where($where)->count();
        $page = new Page($count, 15);
        $show = $page->show();
        $list = $daily_sign->where($where)->limit($page->firstRow . ',' . $page->listRows)->order('id desc')
            ->select();
        if(!empty($list)){
            foreach ($list as &$value) {
                $value['link'] = C('SITE_URL').'/Wap/DailySign/index?id='.$value['id'];
            }
        }
        $this->assign('page', $show);
        $this->assign('list', $list);
        $this->display();
    }

    public function statusDailySign()
    {
        $status = I('get.status', DailySignModel::SIGN_STATUS_ACTIVE);
        $where['id'] = I('get.id', -1);
        if($status == 'active'){
            M('daily_sign')->where($where)->save(array('status' => DailySignModel::SIGN_STATUS_ACTIVE));
            $message = '发布成功';
        }elseif($status == 'stop'){
            M('daily_sign')->where($where)->save(array('status' => DailySignModel::SIGN_STATUS_STOP));
            $message = '停用成功';
        }else {
            M('daily_sign')->where($where)->save(array('status' => DailySignModel::SIGN_STATUS_DELETE));
            $message = '删除成功';
        }
        $this->success($message, '', true);
    }

    public function edit()
    {
        $id = I('get.id', -1);
        $step = I('get.step', 1);
        $where['id'] = $id;
        $where['token'] = $this->wxuser['token'];
        $daily_sign = M('daily_sign')->where($where)->find();
        if($step == 1){
            //图库
            $where_son1["token"] = $this->wxuser['token'];
            $where_son2["has_share"] = DailySignModel::HAS_SHARE_YES;
            $where_image['_complex'] = array(
                $where_son1,
                $where_son2,
                '_logic' => 'or'
            );
            $where_image['type'] = DailySignModel::ATTACH_TYPE_IMG;
            $where_image['status'] = DailySignModel::ATTACH_STATUS_ACTIVE;
            $images = M('daily_sign_attach')->where($where_image)->field('id,title')->select();
            //语录库
            $where_word['_complex'] = array(
                $where_son1,
                $where_son2,
                '_logic' => 'or'
            );
            $where_word['type'] = DailySignModel::ATTACH_TYPE_WORD;
            $where_word['status'] = DailySignModel::ATTACH_STATUS_ACTIVE;
            $words = M('daily_sign_attach')->where($where_word)->field('id,title')->select();
            //宜忌文库
            $where_advice['_complex'] = array(
                $where_son1,
                $where_son2,
                '_logic' => 'or'
            );
            $where_advice['type'] = DailySignModel::ATTACH_TYPE_ADVICE;
            $where_advice['status'] = DailySignModel::ATTACH_STATUS_ACTIVE;
            $advices = M('daily_sign_attach')->where($where_advice)->field('id,title')->select();
            $this->assign('images', $images);
            $this->assign('words', $words);
            $this->assign('advices', $advices);
        }elseif($step == 2){
            $continue_rules = $total_rules = array();
            $continue_rule = json_decode($daily_sign['continue_rule']);
            $total_rule = json_decode($daily_sign['total_rule']);
            if(!empty($continue_rule)){
                foreach ($continue_rule as $cr){
                    $rule = explode(',', $cr);
                    $continue_rules[] = array(
                        'value' => $cr,
                        'text' => '连续'.$rule[0].'天，每日加送'.$rule[1].'分',
                    );
                }
            }
            if(!empty($total_rule)){
                foreach ($total_rule as $tr){
                    $rule = explode(',', $tr);
                    $total_rules[] = array(
                        'value' => $tr,
                        'text' => '累计'.$rule[0].'天，每日加送'.$rule[1].'分',
                    );
                }
            }
            $this->assign('continue_rules', $continue_rules);
            $this->assign('total_rules', $total_rules);
        }else{
            $where_custom['sign_id'] = $id;
            $where_custom['status'] = DailySignModel::CUSTOM_STATUS_ACTIVE;
            $count = M('daily_sign_custom')->where($where_custom)->count();
            $page = new Page($count, 15);
            $show = $page->show();
            $list = M('daily_sign_custom')->where($where_custom)->limit($page->firstRow . ',' . $page->listRows)
                ->order('id desc')->select();
            $this->assign('page', $show);
            $this->assign('list', $list);
        }
        $this->assign('id', $id);
        $this->assign('step', $step);
        $this->assign('daily_sign', $daily_sign);
        $this->display();
    }

    public function updateStep1()
    {
        $id = I('post.id', -1);
        $title = I('post.title', '');
        $type = I('post.type', 1);
        $attach_word = I('post.attach_word', -1);
        $attach_image = I('post.attach_image', -1);
        $attach_advice = I('post.attach_advice', -1);
        $word_sort = I('post.word_sort', 1);
        $image_sort = I('post.image_sort', 1);
        $advice_sort = I('post.advice_sort', 1);
        $has_weather = I('post.has_weather', DailySignModel::HAS_WEATHER_NO);
        $has_festival = I('post.has_festival', DailySignModel::HAS_FESTIVAL_NO);
        if($title == '' || $attach_word == 0 || $attach_advice == 0){
            $this->ajaxReturn(array('code' => -1, 'errMsg' => 'fail'));
        }
        if($attach_image == 0 && $type == DailySignModel::CALENDAR_TYPE_2){
            $this->ajaxReturn(array('code' => -1, 'errMsg' => 'fail'));
        }
        $data = array(
            'token' => $this->wxuser['token'],
            'title' => $title,
            'type' => $type,
            'attach_word' => $attach_word,
            'attach_image' => $attach_image,
            'attach_advice' => $attach_advice,
            'word_sort' => $word_sort,
            'image_sort' => $image_sort,
            'advice_sort' => $advice_sort,
            'has_weather' => $has_weather,
            'has_festival' => $has_festival
        );
        if($id == -1){
            $added = M('daily_sign')->add($data);
            if($added !== false){
                $this->ajaxReturn(array('code' => 0, 'errMsg' => 'ok', 'id' => $added));
            }else{
                $this->ajaxReturn(array('code' => -2, 'errMsg' => 'fail'));
            }
        }else{
            $where['id'] = $id;
            $updated = M('daily_sign')->where($where)->save($data);
            if($updated !== false){
                $this->ajaxReturn(array('code' => 0, 'errMsg' => 'ok', 'id' => $id));
            }else{
                $this->ajaxReturn(array('code' => -2, 'errMsg' => 'fail'));
            }
        }
    }

    public function updateCredit()
    {
        $id = I('post.id', -1);
        $daily_credit = I('post.daily_credit', 0);
        $share_credit = I('post.share_credit', 0);
        $continue_rule = I('post.continue_rule', '');
        $total_rule = I('post.total_rule', '');
        if($id == -1){
            $this->ajaxReturn(array('code' => -1, 'errMsg' => 'fail'));
        }
        $data = array(
            'daily_credit' => $daily_credit,
            'share_credit' => $share_credit,
            'continue_rule' => $continue_rule,
            'total_rule' => $total_rule
        );
        $where['id'] = $id;
        $updated = M('daily_sign')->where($where)->save($data);
        if($updated !== false){
            $this->ajaxReturn(array('code' => 0, 'errMsg' => 'ok'));
        }else{
            $this->ajaxReturn(array('code' => -2, 'errMsg' => 'fail'));
        }
    }

    //添加个性化设置
    public function updateCustom()
    {
        $id = I('post.id', -1);
        $custom_id = I('post.custom_id', -1);
        $custom_date = I('post.custom_date', '');
        $custom_word = I('post.custom_word', '');
        $custom_author = I('post.custom_author', '');
        $advice_type = I('post.advice_type', 0);
        $custom_advice = I('post.custom_advice', '');
        $custom_image = I('post.custom_image', '');
        if($id == -1){
            $this->ajaxReturn(array('code' => -1, 'errMsg' => 'fail'));
        }
        if($custom_id == -1){
            $where_custom['sign_id'] = $id;
            $where_custom['date'] = $custom_date;
            $where_custom['status'] = DailySignModel::CUSTOM_STATUS_ACTIVE;
            $custom = M('daily_sign_custom')->where($where_custom)->order('id desc')->find();
            if(!empty($custom)){
                $this->ajaxReturn(array('code' => -1, 'errMsg' => 'fail'));
            }
        }
        $data = array(
            'sign_id' => $id,
            'date' => $custom_date,
            'word' => $custom_word,
            'author' => $custom_author,
            'advice' => $custom_advice,
            'advice_type' => $advice_type,
            'image' => $custom_image,
        );
        if($custom_id == -1){
            $added = M('daily_sign_custom')->add($data);
            if($added !== false){
                $this->ajaxReturn(array('code' => 0, 'errMsg' => 'ok'));
            }else{
                $this->ajaxReturn(array('code' => -2, 'errMsg' => 'fail'));
            }
        }else{
            $where['id'] = $custom_id;
            $updated = M('daily_sign_custom')->where($where)->save($data);
            if($updated !== false){
                $this->ajaxReturn(array('code' => 0, 'errMsg' => 'ok'));
            }else{
                $this->ajaxReturn(array('code' => -2, 'errMsg' => 'fail'));
            }
        }
    }

    public function statusCustom()
    {
        $where['id'] = I('get.id', -1);
        M('daily_sign_custom')->where($where)->save(array('status' => DailySignModel::CUSTOM_STATUS_DELETE));
        $message = '删除成功';
        $this->success($message, '', true);
    }

    //分享设置
    public function setting()
    {
        $id = I('get.id', -1);
        if(IS_POST){
            $id = I('post.id', -1);
            $share_title = I('post.share_title', '【时间】【昵称】领取了心情日历签，快来领取你的心情日历签');
            $share_desc = I('post.share_desc', '【昵称】【宜忌】');
            $share_link = I('post.share_link', C('SITE_URL').'/Wap/DailySign/index?id='.$id);
            $share_image = I('post.share_image', '/Public/images/daily_sign/share_daily_sign.png');
            $data  = array(
                'share_title' => $share_title,
                'share_desc' => $share_desc,
                'share_link' => $share_link,
                'share_image' => $share_image
            );
            $where['id'] = $id;
            $updated = M('daily_sign')->where($where)->save($data);
            if($updated !== false){
                $this->success('操作成功', '/User/DailySign/index');
            }else{
                $this->error('操作失败');
            }
        }else{
            $where['id'] = $id;
            $daily_sign = M('daily_sign')->where($where)->find();
            if($daily_sign['share_title'] == ''){
                $daily_sign['share_title'] = '【时间】【昵称】领取了心情日历签，快来领取你的心情日历签';
            }
            if($daily_sign['share_desc'] == ''){
                $daily_sign['share_desc'] = '【昵称】【宜忌】';
            }
            if($daily_sign['share_link'] == ''){
                $daily_sign['share_link'] = C('SITE_URL').'/Wap/DailySign/index?id='.$id;
            }
            if($daily_sign['share_image'] == ''){
                $daily_sign['share_image'] = '/Public/images/daily_sign/share_daily_sign.png';
            }
            $this->assign('id', $id);
            $this->assign('daily_sign', $daily_sign);
            $this->display();
        }
    }

    //语录库
    public function attach()
    {
        $type = I('get.type', 1);
        $title = I('get.title', '');
        $creator = I('get.creator', '');
        $where_son1["token"] = $this->wxuser['token'];
        $where_son2["has_share"] = DailySignModel::HAS_SHARE_YES;
        $where['_complex'] = array(
            $where_son1,
            $where_son2,
            '_logic' => 'or'
        );
        $where['type'] = $type;
        $where['status'] = DailySignModel::ATTACH_STATUS_ACTIVE;
        if($title){
            $where['title'] = $title;
            $this->assign('title', $title);
        }
        if($creator){
            $where['creator'] = $creator;
            $this->assign('creator', $creator);
        }
        $count = M('daily_sign_attach')->where($where)->count();
        $page = new Page($count, 15);
        $show = $page->show();
        $list = M('daily_sign_attach')->where($where)->
            limit($page->firstRow . ',' . $page->listRows)->order('id desc')->select();
        if(!empty($list)){
            foreach ($list as &$value){
                $value['createdate'] = date('Y-m-d', strtotime($value['createdate']));
            }
        }
        $this->assign('page', $show);
        $this->assign('type', $type);
        $this->assign('list', $list);
        $this->display();
    }

    public function addAttach()
    {
        $title = I('post.title', '');
        $has_share = I('post.has_share', DailySignModel::HAS_SHARE_NO);
        $type = I('post.type', -1);
        if($title == ''){
            $this->ajaxReturn(array('code' => -1, 'errMsg' => 'fail'));
        }
        $data = array(
            'token' => $this->wxuser['token'],
            'type' => $type,
            'title' => $title,
            'creator' => session("uname"),
            'has_share' => $has_share
        );
        $added = M('daily_sign_attach')->add($data);
        if($added !== false){
            $this->ajaxReturn(array('code' => 0, 'errMsg' => 'ok'));
        }else{
            $this->ajaxReturn(array('code' => -2, 'errMsg' => 'fail'));
        }
    }

    public function updateAttachTitle()
    {
        $id = I('post.attach_id', -1);
        $title = I('post.attach_title', '');
        if($id == -1 || $title == ''){
            $this->ajaxReturn(array('code' => -1, 'errMsg' => 'fail'));
        }
        $where['id'] = $id;
        $updated = M('daily_sign_attach')->where($where)->save(array('title' => $title));
        if($updated !== false){
            $this->ajaxReturn(array('code' => 0, 'errMsg' => 'ok'));
        }else{
            $this->ajaxReturn(array('code' => -2, 'errMsg' => 'fail'));
        }
    }

    public function statusAttach()
    {
        $where['id'] = I('get.id', -1);
        M('daily_sign_attach')->where($where)->save(array('status' => DailySignModel::ATTACH_STATUS_DELETE));
        $message = '删除成功';
        $this->success($message, '', true);
    }

    public function attachment()
    {
        $attach_id = I('get.attach_id', -1);
        $content_or_author = I('get.content_or_author', '');
        $where_attach['id'] = $attach_id;
        $attach = M('daily_sign_attach')->where($where_attach)->find();
        $where_attachment['attach_id'] = $attach_id;
        $where_attachment['status'] = DailySignModel::ATTACHMENT_STATUS_ACTIVE;
        if($content_or_author){
            $where_son1["content"] = array('LIKE', "%" . $content_or_author . "%");
            $where_son2["author"] = array('LIKE', "%" . $content_or_author . "%");
            $where_attachment['_complex'] = array(
                $where_son1,
                $where_son2,
                '_logic' => 'or'
            );
            $this->assign('content_or_author', $content_or_author);
        }
        $count = M('daily_sign_attachment')->where($where_attachment)->count();
        $page = new Page($count, 24);
        $show = $page->show();
        $list = M('daily_sign_attachment')->where($where_attachment)
            ->limit($page->firstRow . ',' . $page->listRows)->order('id desc')->select();
        $this->assign('page', $show);
        $this->assign('attach_id', $attach_id);
        $this->assign('type', $attach['type']);
        $this->assign('attach', $attach);
        $this->assign('list', $list);
        $this->display();
    }

    public function updateAttachment()
    {
        $attachment_id = I('post.attachment_id', -1);
        $attach_id = I('post.attach_id', -1);
        $type = I('post.type', DailySignModel::ATTACH_TYPE_WORD);
        $content = I('post.content', '');
        $author = I('post.author', '');
        $advice_content = I('post.advice_content', '');
        $advice_type = I('post.advice_type', DailySignModel::ATTACHMENT_TYPE_GOOD);
        if($type == DailySignModel::ATTACH_TYPE_WORD){
            if($attach_id == -1 || $content == ''){
                $this->ajaxReturn(array('code' => -1, 'errMsg' => 'fail'));
            }
            $data = array(
                'attach_id' => $attach_id,
                'content' => $content,
                'author' => $author
            );
        }elseif($type == DailySignModel::ATTACH_TYPE_IMG){
            $data = array();
        }else{
            if($attach_id == -1 || $advice_content == ''){
                $this->ajaxReturn(array('code' => -1, 'errMsg' => 'fail'));
            }
            $data = array(
                'attach_id' => $attach_id,
                'content' => $advice_content,
                'type' => $advice_type
            );
        }
        if($attachment_id == -1){
            $added = M('daily_sign_attachment')->add($data);
            if($added !== false){
                $this->ajaxReturn(array('code' => 0, 'errMsg' => 'ok'));
            }else{
                $this->ajaxReturn(array('code' => -2, 'errMsg' => 'fail'));
            }
        }else{
            $where['id'] = $attachment_id;
            $updated = M('daily_sign_attachment')->where($where)->save($data);
            //更新缓存
            $where_daily_sign['token'] = $this->wxuser['token'];
            $where_daily_sign['status'] = array('neq', DailySignModel::SIGN_STATUS_DELETE);
            $daily_sign_list = M('daily_sign')->where($where_daily_sign)->field('id')->select();
            if(!empty($daily_sign_list)){
                foreach ($daily_sign_list as $value){
                    if($type == DailySignModel::ATTACH_TYPE_ADVICE){
                        $advice_cache = S('daily_sign_advice_'.date('Y-m-d').'_'.$value['id']);
                        if($advice_cache && $advice_cache['id'] == $attachment_id){
                            S('daily_sign_advice_'.date('Y-m-d').'_'.$value['id'], array('id' => $attachment_id,
                                'advice_type' => $data['type'], 'advice' => $data['content']), 24*60*60);
                        }
                    }
                }
            }
            if($updated !== false){
                $this->ajaxReturn(array('code' => 0, 'errMsg' => 'ok'));
            }else{
                $this->ajaxReturn(array('code' => -2, 'errMsg' => 'fail'));
            }
        }
    }

    public function statusAttachment()
    {
        //更新缓存
        $where_daily_sign['token'] = $this->wxuser['token'];
        $where_daily_sign['status'] = array('neq', DailySignModel::SIGN_STATUS_DELETE);
        $daily_sign_list = M('daily_sign')->where($where_daily_sign)->field('id')->select();
        if(!empty($daily_sign_list)){
            foreach ($daily_sign_list as $value){
                $advice_cache = S('daily_sign_advice_'.date('Y-m-d').'_'.$value['id']);
                $image_cache = S('daily_sign_image_'.date('Y-m-d').'_'.$value['id']);
                if($advice_cache){
                    S('daily_sign_advice_'.date('Y-m-d').'_'.$value['id'], NULL);
                }
                if($image_cache){
                    S('daily_sign_image_'.date('Y-m-d').'_'.$value['id'], NULL);
                }
            }
        }

        $where['id'] = I('get.id', -1);
        M('daily_sign_attachment')->where($where)->save(array('status' => DailySignModel::ATTACHMENT_STATUS_DELETE));
        $message = '删除成功';
        $this->success($message, '', true);
    }

    //ajax上传图片
    public function uploadImage()
    {
        $image = I('post.image', '');
        if($image == ''){
            $this->ajaxReturn(array('code' => -1, 'errMsg' => 'img upload fail'));
        }
        $ret = FactoryModel::ajaxImgUpload($image, 'daily_sign');
        if($ret['code'] == -1){
            $this->ajaxReturn(array('code' => -1, 'errMsg' => 'img upload fail'));
        }
        $this->ajaxReturn(array('code' => 0, 'msg' => $ret['msg']));
    }

    //保存所有图片
    public function uploadImages()
    {
        $attach_id = I('post.attach_id', -1);
        $images = I('post.images', '');
        if($images == ''){
            $this->error('上传图片不能为空，操作失败', '/User/DailySign/attachment?attach_id='.$attach_id);
        }
        $images = explode(',', $images);
        if(!empty($images)){
            $data = array();
            foreach ($images as $value){
                $data[] = array(
                    'attach_id' => $attach_id,
                    'content' => $value
                );
            }
            $added = M('daily_sign_attachment')->addAll($data);
            if($added !== false){
                $this->success('操作成功', '/User/DailySign/attachment?attach_id='.$attach_id);
            }else{
                $this->error('操作失败', '/User/DailySign/attachment?attach_id='.$attach_id);
            }
        }else{
            $this->error('上传图片不能为空，操作失败', '/User/DailySign/attachment?attach_id='.$attach_id);
        }
    }

    //上传文件
    private function _upload()
    {
        $upload = new \Think\Upload();// 实例化上传类
        $upload->maxSize = 3145728;// 设置附件上传大小
        $upload->exts = array('jpg', 'gif', 'png', 'jpeg', 'mp3', 'mp4', 'wav', 'xls', 'xlsx', 'csv');// 设置附件上传类型
        $upload->rootPath = './Public/Uploads/daily_sign/'; // 设置附件上传根目录
        $upload->subName = array('date', 'Ymd');
        $upload->saveName = array('uniqid', 'dailysign');
        $info = $upload->upload();
        if($info['picurl1']['savename']){
            $picurl = '/Public/Uploads/daily_sign/'.date('Ymd').'/'.$info['picurl1']['savename'];
        }else{
            $picurl = I('post.pic1', '');
        }
        return $picurl;
    }

    //上传excel
    public function uploadExcel()
    {
        set_time_limit(0);
        $attach_id = I('post.attach_id', -1);
        $type = I('post.type', -1);
        if($attach_id == -1){
            $this->redirect('/User/DailySign/index');
        }
        $upload = $this->_upload();
        if($upload == ''){
            $this->error('上传文件不能为空，操作失败', '/User/DailySign/attachment?attach_id='.$attach_id);
        }
        $filename = './'.$upload;
        vendor('phpexcel.PHPExcel');
        $extension = strtolower( pathinfo($filename, PATHINFO_EXTENSION) );
        if ($extension =='xlsx') {
            $objReader = new \PHPExcel_Reader_Excel2007();
            $objExcel = $objReader->load($filename);
        } else if ($extension =='xls') {
            $objReader = new \PHPExcel_Reader_Excel5();
            $objExcel = $objReader->load($filename);
        } else if ($extension=='csv') {
            $PHPReader = new \PHPExcel_Reader_CSV();
            $PHPReader->setInputEncoding('GBK');
            $PHPReader->setDelimiter(',');
            $objExcel = $PHPReader->load($filename);
        } else {
            $this->error('仅支持xls、xlsx、csv格式的文件，操作失败', '/User/DailySign/attachment?attach_id='.$attach_id);
        }
        $sheet = $objExcel->getSheet(0);                 // 读取第一个工作表
        $highestRow = $sheet->getHighestRow();           // 取得总行数
        $highestColumn = $sheet->getHighestColumn();     // 取得总列数

        $arr = array('A','B','C','D','E','F','G','H','I','J','K','L','M', 'N','O','P','Q','R','S','T','U','V','W','X','Y','Z');
        // 一次读取一列
        $res_arr = array();
        for ($row = 2; $row <= $highestRow; $row++) {
            $row_arr = array();
            for ($column = 0; $arr[$column] != 'C'; $column++) {
                $val = $sheet->getCellByColumnAndRow($column, $row)->getValue();
                $row_arr[] = $val;
            }
            $res_arr[] = $row_arr;
        }
        if($res_arr){
            $data = array();
            if($type == DailySignModel::ATTACH_TYPE_WORD){
                foreach ($res_arr as $value){
                    $data[] = array(
                        'attach_id' => $attach_id,
                        'content' => $value[0],
                        'author' => ($value[1]=='无') ? '' : $value[1]
                    );
                }
            }elseif($type == DailySignModel::ATTACH_TYPE_IMG){

            }else{
                foreach ($res_arr as $value){
                    $data[] = array(
                        'attach_id' => $attach_id,
                        'content' => $value[0],
                        'type' => ($value[1]=='宜') ? DailySignModel::ATTACHMENT_TYPE_GOOD :
                            DailySignModel::ATTACHMENT_TYPE_BAD
                    );
                }
            }
            //插入sql
            $added = M('daily_sign_attachment')->addAll($data);
            if($added !== false){
                $this->success('操作成功', '/User/DailySign/attachment?attach_id='.$attach_id);
            }else{
                $this->success('操作失败', '/User/DailySign/attachment?attach_id='.$attach_id);
            }
        }else{
            $this->error('上传文件不能为空，操作失败', '/User/DailySign/attachment?attach_id='.$attach_id);
        }
    }

    //导出excel
    public function exportExcel()
    {
        set_time_limit(0);
        $attach_id = I("get.attach_id", -1);
        $type = I("get.type", DailySignModel::ATTACH_TYPE_WORD);
        if($attach_id == -1){
            $this->redirect("/User/DailySign/index");
        }
        $where['attach_id'] = $attach_id;
        $where['status'] = DailySignModel::ATTACHMENT_STATUS_ACTIVE;
        $list = M('daily_sign_attachment')->where($where)->order('id desc')->select();
        vendor('phpexcel.PHPExcel');
        $objExcel = new \PHPExcel();
        $objActSheet = $objExcel->getActiveSheet();
        $objActSheet->getColumnDimension('A')->setWidth(100);
        $objActSheet->getColumnDimension('B')->setWidth(30);
        $objActSheet->setCellValue('A1', "语录");
        if($type == DailySignModel::ATTACH_TYPE_WORD){
            $objActSheet->setCellValue('B1', "作者");
        }elseif($type == DailySignModel::ATTACH_TYPE_IMG){

        }else{
            $objActSheet->setCellValue('B1', "类型");
        }
        $line = 2;
        if(!empty($list)){
            foreach ($list as $value) {
                $objActSheet->setCellValue('A' . $line, $value['content']);
                if($type == DailySignModel::ATTACH_TYPE_WORD){
                    $objActSheet->setCellValue('B' . $line, $value['author']);
                }elseif($type == DailySignModel::ATTACH_TYPE_IMG){

                }else{
                    $advice_type = ($value['type']==DailySignModel::ATTACHMENT_TYPE_GOOD) ? '宜' : '忌';
                    $objActSheet->setCellValue('B' . $line, $advice_type);
                }
                $objActSheet->getRowDimension($line)->setRowHeight(20);
                $line++;
            }
        }
        $fileName = '导出数据' . date('Ymd') . '.xlsx';
        header('Content-Type: application/vnd.ms-excel');
        header("Content-Disposition: attachment;filename=\"$fileName\"");
        header('Cache-Control: max-age=0');
        $objWriter = new \PHPExcel_Writer_Excel2007($objExcel);
        $objWriter->save('php://output');
    }

    public function statistics()
    {
        $id = I('get.id', -1);
        $where['id'] = $id;
        $daily_sign = M('daily_sign')->where($where)->find();
        //折线图
        $range = date('Y-m-d', strtotime('-6 day')).' ~ '.date('Y-m-d');
        $range_date = I('get.range_date', $range);
        $this->assign('range_date', $range_date);
        $ranges = explode(' ~ ', $range_date);
        $start_time = strtotime($ranges[0]);
        $end_time = strtotime($ranges[1]);
//        $start_date = date('Y-m-d H:i:s', $start_time);
//        $end_date = date('Y-m-d H:i:s');
        $dateList = $list = array();
        while($start_time <= $end_time){
            $dateList[] = date('Y-m-d', $end_time);
            $end_time = $end_time - 3600 * 24;
        }
        krsort($dateList);
        $stats = StatisticsModel::getdaterange_list('daily_sign', $id, $ranges[0], $ranges[1]);
        $pv_count = $uv_count = 0;
        if(!empty($dateList)){
            foreach ($dateList as $value){
                $list[] = array(
                    'date' => date('m-d', strtotime($value)),
                    'pv' => isset($stats[$value]['pv_num']) ? $stats[$value]['pv_num'] : 0,
                    'uv' => isset($stats[$value]['uv_num']) ? $stats[$value]['uv_num'] : 0,
                );
                if(isset($stats[$value]['pv_num'])) $pv_count += $stats[$value]['pv_num'];
                if(isset($stats[$value]['uv_num'])) $uv_count += $stats[$value]['uv_num'];
            }
        }
        $count = count($list);
        $list = json_encode($list);
        $this->assign('count', $count);
        $this->assign('list', $list);
        $this->assign('pv_count', $pv_count);
        $this->assign('uv_count', $uv_count);
        $this->assign('id', $id);
        $this->assign('daily_sign', $daily_sign);
        $this->display();
    }

    public function statisticsUser()
    {
        $id = I('get.id', -1);
        $where_daily_sign['id'] = $id;
        $daily_sign = M('daily_sign')->where($where_daily_sign)->find();
        $where['sign_id'] = $id;
        $where['status'] = array('neq', DailySignModel::USER_STATUS_DELETE);
        $count = M('daily_sign_user')->where($where)->count();
        $page = new Page($count, 15);
        $show = $page->show();
        $list = M('daily_sign_user')->where($where)
            ->limit($page->firstRow . ',' . $page->listRows)->order('id desc')->select();
        if(!empty($list)){
            $openids = array();
            foreach ($list as $value){
                $openids[] = $value['openid'];
            }
            $where['openid'] = array('in', $openids);
            $records = M('daily_sign_record')->where($where)->order('id asc')->select();
            $record = array();
            if(!empty($records)){
                foreach ($records as $value){
                    $record[$value['openid']]['recent_time'] = $value['createdate'];
                    $record[$value['openid']]['sign_count'] += 1;
                }
            }
            foreach ($list as &$value){
                $value['recent_time'] = $record[$value['openid']]['recent_time'];
                $value['sign_count'] = $record[$value['openid']]['sign_count'];
            }
        }
        $this->assign('page', $show);
        $this->assign('list', $list);
        $this->assign('id', $id);
        $this->assign('daily_sign', $daily_sign);
        $this->display('statistics_user');
    }

    public function statusUser()
    {
        $id = I('get.id', -1);
        $status = I('get.status', DailySignModel::USER_STATUS_ACTIVE);
        $where['id'] = $id;
        $user = M('daily_sign_user')->where($where)->find();
        if($status == 'delete'){
            M('daily_sign_user')->where($where)->save(array('status' => DailySignModel::USER_STATUS_DELETE));
            $where_record['sign_id'] = $user['sign_id'];
            $where_record['openid'] = $user['openid'];
            M('daily_sign_record')->where($where_record)->save(array('status' => DailySignModel::RECORD_STATUS_DELETE));
            $message = '删除成功';
        }elseif($status == 'black'){
            M('daily_sign_user')->where($where)->save(array('status' => DailySignModel::USER_STATUS_BLACK));
            $message = '加入黑名单成功';
        }else{
            M('daily_sign_user')->where($where)->save(array('status' => DailySignModel::USER_STATUS_ACTIVE));
            $message = '取消黑名单成功';
        }
        $this->success($message, '', true);
    }

    //todo 分页显示数量没改
    //共享没做
    //continue total 天数判断重复
}